from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, HttpResponse
from django.urls import reverse
from .models import Title, Content, MyUser
from .forms import TitleForm, ContentForm, UserForm
from .bkmiddleware import BkMiddleware
from django.core.paginator import Paginator
from django.http import Http404
from .code import check_code
from hashlib import md5

# Create your views here.

def title(request):
    """主页"""
    """搜索"""
    data_dict = {}
    value = request.GET.get('search')
    if value:
        data_dict['title__contains'] = value
    # all_list = Title.objects.filter(title__contains=value).all()
    """获取当前登录用户的id"""
    a = request.session['bkuser']
    b = MyUser.objects.filter(username=a)
    c = ''
    for i in b:
        c = i.id

    """分页"""
    title_pg = Title.objects.filter(owner=c, **data_dict).order_by('-date_add')
    paginator = Paginator(title_pg, 5)  # 获取分页器对象
    last_page = paginator.page_range[-1]  # 获取当前最后一页
    num_p = request.GET.get('page', 1)  # 以page为键得到默认的页面1
    page = paginator.page(int(num_p))  # 获取当前页的page对象

    return render(request, 'title.html', locals())


def nr(request, nid):
    """标题内内容"""
    nid = Title.objects.get(id=nid)
    nr1 = nid.content_set.order_by('date_add')
    context = {'nr1': nr1, 'nid': nid}
    return render(request, 'nr.html', context)


def title_delete(request):
    nid = request.GET.get('nid')
    nid = Title.objects.get(id=nid)
    nid.delete()
    return redirect('/')

# --------------------------------------------------------
def title_add(request):
    """获取当前登录者的ID"""
    name = request.session.get('bkuser')
    print('登录者的名字',name)
    owner_name = MyUser.objects.get(username=name)
    print('登录者的ID',owner_name.id)

    if request.method == 'GET':
        return render(request, 'title_add.html')
    else:
        tit = request.POST.get('tit')
        if not tit:
            return redirect('/title_add/')
        else:
            t = Title.objects.create(title=tit, owner_id=owner_name.id)
            t.save()
        return redirect('/')

# ----------------------------------------------------
def title_edit(request, title_id):
    title = Title.objects.get(id=title_id)
    if request.method != 'POST':
        form = TitleForm(instance=title)
    else:
        form = TitleForm(data=request.POST, instance=title)
        if form.is_valid():
            form.save()
            return redirect('/')
    context = {'title': title, 'form': form}
    return render(request, 'title_edit.html', context)


def nr_add(request, title_id):
    title_id = Title.objects.get(id=title_id)
    if request.method != 'POST':
        form = ContentForm()
    else:
        form = ContentForm(data=request.POST)
        if form.is_valid():
            new_nr = form.save(commit=False)
            new_nr.title = title_id
            new_nr.save()
            return redirect('/nr/{}/'.format(title_id.id))
    context = {'title_id': title_id, 'form': form}
    return render(request, 'nr_add.html', context)


def nr_delete(request):
    nid = request.GET.get('nid')
    nid = Content.objects.get(id=nid)
    tit = Title.objects.get(id=nid.title_id)
    nid.delete()

    return redirect('/nr/{}/'.format(tit.id))


# 图片验证码
from io import BytesIO


def image_code(request):
    img, code_string = check_code()
    # print(code_string)  # 验证码
    request.session['code_s'] = code_string
    request.session.set_expiry(60)  # 设置60秒超时
    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())



def login(request):
    if request.method != 'POST':
        return render(request, 'login.html')
    else:
        name = request.POST['name']
        pwd = request.POST['pwd']
        """将密码转换为MD5加密"""
        pwd = md5(pwd.encode('utf-8')).hexdigest()

        yzm = request.POST['yzm']
        if request.session['code_s'] != yzm:
            return render(request, 'login.html', {'err': '验证码错误'})
        request.session.set_expiry(3600 * 24)
        try:
            name2 = MyUser.objects.get(username=name)
            if name2 and name2.password == pwd:
                request.session['bkuser'] = name
                return redirect('/')
        except Exception as e:
            return render(request, 'login.html', {'err': '用户不存在'})
        return render(request, 'login.html', {'err': '密码错误'})


"""基于form表单登录"""
def login_form(request):
    if request.method != 'POST':
        form = UserForm()
    form = UserForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/')
    return render(request, 'login_form.html', locals())


def register(request):
    if request.method != 'POST':
        return render(request, 'register.html')
    name = request.POST['name']
    pwd = request.POST['pwd']
    pwd2 = request.POST['pwd2']
    username = MyUser.objects.all()
    for i in username:
        if i.username == name:
            return render(request, 'register.html', {'err': '用户名已存在'})
    if pwd == '':
        return render(request, 'register.html', {'err': '请输入密码'})
    elif len(pwd) < 6:
        return render(request, 'register.html', {'err': '密码小于6位'})
    elif pwd != pwd2:
        return render(request, 'register.html', {'err': '密码不一致'})
    """将密码用MD5加密"""
    pwd = md5(pwd.encode('utf-8')).hexdigest()

    MyUser.objects.create(username=name, password=pwd)
    return redirect('/ok/')


def logout(request):
    request.session.clear()
    return redirect('/login/')


def nr_edit(request, nr_id):
    nr = Content.objects.get(id=nr_id)
    # nr_id = nr.title
    if request.method != 'POST':
        form = ContentForm(instance=nr)
    else:
        form = ContentForm(data=request.POST, instance=nr)
        if form.is_valid():
            form.save()
            return redirect('/nr/{}/'.format(nr.title_id))
    context = {'form': form, 'nr_id': nr_id, 'nr': nr}
    return render(request, 'nr_edit.html', context)


def register_ok(request):
    return render(request, 'ok.html')


